package com.wumeng.dynamicmultidatabase01.modules.user.controller;

import com.wumeng.dynamicmultidatabase01.config.DBContextHolder;
import com.wumeng.dynamicmultidatabase01.modules.user.dao.User;
import com.wumeng.dynamicmultidatabase01.modules.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;


/**
 * @author wumeng 2022/6/8 4:35 下午
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private UserService userService;

    @RequestMapping(value = "/query_user", method = RequestMethod.GET)
    public User queryUserById(int id, String client) {
        logger.info("查询id = " + id);
        if (client == null | client.isEmpty()) {
            //默认
            client = "testdb";
        }
        DBContextHolder.setCurrentDb(client);


        return this.userService.queryUserById(id);
    }

    @RequestMapping(value = "/deleteUser", method = RequestMethod.GET)
    public String deleteUserById(int id, String client) {
        if (client == null | client.isEmpty()) {
            //默认
            client = "testdb";
        }
        DBContextHolder.setCurrentDb(client);

        this.userService.deleteById(id);
        logger.info("删除id" + id);
        return "删除成功";
    }

    //    @RequestMapping( value = "/addUser", method = RequestMethod.GET)
    @GetMapping("/addUser/{id}")
    public String addUser(@PathVariable(value = "id") Integer id, @RequestParam(value = "name") String name , String client) {

        if (client == null | client.isEmpty()) {
            //默认
            client = "testdb";
        }
        DBContextHolder.setCurrentDb(client);

        User user = new User();
        user.setName(name);
        user.setCreate_time(new Timestamp(System.currentTimeMillis()));
        int addCode = this.userService.add(user);
        logger.info("id " + id + "add code " + addCode);
        return "添加成功";
    }


}


